from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import Profile

User = get_user_model()


# 需要修改apps.py, __init__.py文件，才能生效

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kw):
    """当创建用户的时候，自动创建个人中心(profile)"""
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_profile(sender, instance, **kw):
    """当每次用户save时执行该函数"""
    instance.profile.save()
